package com.bookbuf.social.share.content.media.image;

import android.content.Context;
import android.graphics.Bitmap;

import com.bookbuf.social.share.content.media.BaseMediaObject;
import com.bookbuf.social.share.content.media.image.converter.BinaryConverter;
import com.bookbuf.social.share.content.media.image.converter.BitmapConverter;
import com.bookbuf.social.share.content.media.image.converter.ConfiguredConverter;
import com.bookbuf.social.share.content.media.image.converter.ConvertConfig;
import com.bookbuf.social.share.content.media.image.converter.FileConverter;
import com.bookbuf.social.share.content.media.image.converter.ResConverter;
import com.bookbuf.social.share.content.media.image.converter.UrlConverter;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * 图片媒介
 */
public class ImageMedia extends BaseMediaObject {


	private ConfiguredConverter converter = null;
	private WeakReference<Context> weakReference = null;


	public ImageMedia (WeakReference<Context> weakReference, File file) {
		this.init (weakReference, file);
	}

	private void init (WeakReference<Context> weakReference, Object params) {
		this.weakReference = weakReference;
		if (params instanceof File) {
			this.converter = new FileConverter ((File) params);
		} else if (params instanceof String) {
			this.converter = new UrlConverter ((String) params);
		} else if (params instanceof Integer) {
			this.converter = new ResConverter (weakReference.get (), ((Integer) params).intValue ());
		} else if (params instanceof byte[]) {
			this.converter = new BinaryConverter ((byte[]) (params));
		} else {
			if (!(params instanceof Bitmap)) {
				throw new RuntimeException ("Don\'t support type");
			}

			this.converter = new BitmapConverter ((Bitmap) params);
		}

		this.converter.setConfig (new ConvertConfig (weakReference.get ()));
	}

	public ImageMedia (WeakReference<Context> weakReference, String url) {
		super (url);
		this.init (weakReference, url);
	}

	public ImageMedia (WeakReference<Context> weakReference, int resId) {
		this.init (weakReference, Integer.valueOf (resId));
	}

	public ImageMedia (WeakReference<Context> weakReference, byte[] bytes) {
		this.init (weakReference, bytes);
	}

	public ImageMedia (WeakReference<Context> weakReference, Bitmap bitmap) {
		this.init (weakReference, bitmap);
	}

	@Override
	public MediaType getMediaType () {
		return MediaType.IMAGE;
	}

	public File asFileImage () {
		return this.converter == null ? null : this.converter.asFile ();
	}

	public String asUrlImage () {
		return this.converter == null ? null : this.converter.asUrl ();
	}

	public byte[] asBinImage () {
		return this.converter == null ? null : this.converter.asBinary ();
	}

	public Bitmap asBitmap () {
		return this.converter == null ? null : this.converter.asBitmap ();
	}

	@Override
	public byte[] toByte () {
		return this.asBinImage ();
	}

	@Override
	public boolean isMultiMedia () {
		return true;
	}


}
